package Servlets;

import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.util.LinkedList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Beans.Veiling;
import DAOs.VeilingDAO;
import Database.DBmanager;

/**
 * Servlet implementation class testServlet
 */
public class testServlet extends HttpServlet implements ServletContextListener{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public testServlet() {
        super();
        
       // DBmanager db = DBmanager.getInstance();
        // TODO Auto-generated constructor stub
        
        
    }
    
    

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String requestType = request.getParameter("requestType");
	
		LinkedList<Veiling> veilingen = new VeilingDAO().getAllVeilingen();
		request.setAttribute("veilingen", veilingen);
		
		RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/index.jsp");
		view.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		System.out.println("in testServlet.dopost");
		
		LinkedList<Veiling> veilingen = new VeilingDAO().getAllVeilingen();
		request.setAttribute("veilingen", veilingen);
		
		RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/index.jsp");
		view.forward(request, response);

	}



	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		
	}



	@Override
	public void contextInitialized(ServletContextEvent e) {
//		arg0.getServletContext() <------------ dit is je servletcontext
		Date d = new Date(System.currentTimeMillis());
	
		System.out.println("timetest: " + d.toGMTString());
		System.out.println("in testservlet.contextinitialized");
		System.out.println(this.toString());
		System.out.println("servletcontext bestaat: " + this != null);
		DBmanager.setLocation(
				e.getServletContext().
				getInitParameter("javax.servlet.jsp.jstl.sql.dataSource")
				);
		try {
			if(!DBmanager.getInstance().getConnection().createStatement().execute("SELECT * from Veilingen")){
				DBmanager.getInstance().createDatabase();
			}
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (NullPointerException npe){
			DBmanager.getInstance().createDatabase();
		}
		
	}

}
